﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data;

namespace BasicCMS.Data
{
    public class InsertBuilder : IPersistentBuilder
    {
        private readonly IUnitOfWork unitOfWork;
        private IList<KeyValuePair<string, object>> values = new List<KeyValuePair<string, object>>();
        private string tableName;
        private IDbCommand command;

        public InsertBuilder(IUnitOfWork unitOfWork,string tableName)
        {
            this.unitOfWork = unitOfWork;
            this.tableName = tableName;
        }

        public IDbCommand Command
        {
            set { command = value; }
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public InsertBuilder Value(string name, object value)
        {
            values.Add(new KeyValuePair<string,object>(name,value));
            return this;
        }

        void IPersistentBuilder.Persistent()
        {
            StringBuilder fieldsBuilder = new StringBuilder();
            StringBuilder valueBuidler = new StringBuilder();
            StringBuilder sqlBuilder = new StringBuilder();
            foreach (var item in values)
            {
                fieldsBuilder.AppendFormat("{0},", item.Key);
                valueBuidler.AppendFormat("@{0},", item.Key);
                command.Parameters.Add(new SqlParameter("@" + item.Key, item.Value));
            }
            fieldsBuilder.TrimEnd();
            valueBuidler.TrimEnd();
            sqlBuilder.AppendFormat("INSERT INTO [{0}]({1}) VALUES({2})", tableName, fieldsBuilder, valueBuidler);

            command.CommandText = sqlBuilder.ToString();
            command.ExecuteNonQuery();
        }


        bool IPersistentBuilder.IsValid
        {
            get { return !String.IsNullOrEmpty(tableName) && values.Count > 0; }
        }
}
}
